package com.dev.weixin.manager.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;

import com.dev.security.util.Criteria;
import com.dev.security.util.DataGrid;
import com.dev.weixin.manager.beans.TextTemplate;
import com.dev.weixin.manager.dao.TextTemplateRepository;
import com.dev.weixin.manager.service.ITextTemplateService;
import com.dev.weixin.utils.ObjectUtils;

/**
 * @author 飘渺青衣
 * @see
 */
@Service
public class TextTemplateService implements ITextTemplateService {

	@Autowired
	private TextTemplateRepository textTemplateRepository;
	
	/* (non-Javadoc)
	 * @see com.dev.weixin.manager.service.ITextTemplateService#save(com.dev.weixin.manager.beans.TextTemplate)
	 */
	@Override
	public void save(TextTemplate text) {
		ObjectUtils.trimToEmpty(text);
		this.textTemplateRepository.save(text);
	}

	/* (non-Javadoc)
	 * @see com.dev.weixin.manager.service.ITextTemplateService#findPage(com.dev.weixin.manager.beans.TextTemplate, int, int)
	 */
	@Override
	public DataGrid<TextTemplate> findPage(TextTemplate cond, int page, int size) {
		ObjectUtils.trimToEmpty(cond);
		Criteria<TextTemplate> criteria = new Criteria<TextTemplate>();
		criteria.and().eq("user_id", cond.getUser_id());
		if(StringUtils.isNotEmpty(cond.getName())) {
			criteria.and().like("name", 
					new StringBuilder()
						.append("%").append(cond.getName()).append("%")
						.toString());
		}
		if(StringUtils.isNotEmpty(cond.getContent())) {
			criteria.and().like("content", 
					new StringBuilder()
						.append("%").append(cond.getContent()).append("%")
						.toString());
		}
		Sort sort = new Sort(new Order(Direction.DESC, "createTime"));
		Page<TextTemplate> pager = this.textTemplateRepository
				.findAll(criteria.toSpecifications(), new PageRequest(page > 0 ? page - 1 : 0, size, sort));
		return new DataGrid<TextTemplate>(pager);
	}

	/* (non-Javadoc)
	 * @see com.dev.weixin.manager.service.ITextTemplateService#remove(java.lang.String[])
	 */
	@Override
	public int remove(String[] ids, String user_id) {
		return this.textTemplateRepository.delete(ids, StringUtils.trimToEmpty(user_id));
	}

	/* (non-Javadoc)
	 * @see com.dev.weixin.manager.service.ITextTemplateService#findTextTemplate(java.lang.String)
	 */
	@Override
	public TextTemplate findTextTemplate(String id, String user_id) {
		return this.textTemplateRepository.findOne(StringUtils.trimToEmpty(id));
	}

}
